import yaml
import pymysql
from pymysql import Error

def load_yaml_file(file_path):
    """加载YAML文件"""
    with open(file_path, 'r', encoding='utf-8') as file:
        return yaml.safe_load(file)

def save_to_mysql(data, host, port, user, password, database, table_name):
    """将数据保存到MySQL数据库"""
    try:
        # 连接数据库
        connection = pymysql.connect(
            host=host,
            port=port,
            user=user,
            password=password,
            database=database,
            charset='utf8mb4'
        )
        
        cursor = connection.cursor()
        
        # 插入数据
        insert_sql = f"""
        INSERT INTO {table_name} 
        (meta_name, wind_id, xpath, x_target_name, cum_to_monthly, calc_yoy, unit, `order`, tag)
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
        """
        
        for indicator_name, config in data.items():
            values = (
                indicator_name,
                config.get('wind_id'),
                config.get('xpath'),
                config.get('x_target_name'),
                config.get('cum_to_monthly', False),
                config.get('calc_yoy', False),
                config.get('unit'),
                config.get('order'),
                config.get('tag')
            )
            cursor.execute(insert_sql, values)
        
        connection.commit()
        print(f"成功插入 {len(data)} 条记录到 {table_name} 表")
        
    except Error as e:
        print(f"数据库错误: {e}")
    finally:
        if connection:
            connection.close()

# 主程序
if __name__ == "__main__":
    # 配置参数
    yaml_file_path = 'meta.yaml'
    mysql_config = {
        'host': '172.26.123.143',
        'port': 3306,
        'user': 'user1',
        'password': 'user123456',
        'database': 'my_database',
        'table_name': 'metainfo'
    }
    
    # 加载YAML数据
    meta_data = load_yaml_file(yaml_file_path)
    
    # 保存到MySQL
    save_to_mysql(meta_data, **mysql_config)